#!/usr/bin/python
# -*- coding: iso-8859-1 -*-

#-----------------------------------------
# getlib.py is a part of mahjong-2d project.
# Name:         getlib.py
# Author:       
# Copyright:    (C) 2013 
# Licence:      
# Website:      
# Email:        
#-----------------------------------------


import os
import sys    
import termios
import fcntl
from threading import *
import time

clock = 60
def get_char():
    fd = sys.stdin.fileno()

    oldterm = termios.tcgetattr(fd)
    newattr = termios.tcgetattr(fd)
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, newattr)

    oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

    try:
        while 1:
            try:
                c = sys.stdin.read(1)
                print "Got character", repr(c)
            except IOError:
                pass
    finally:
        print "."
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

def myGetch():
    fd = sys.stdin.fileno()

    oldterm = termios.tcgetattr(fd)
    newattr = termios.tcgetattr(fd)
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, newattr)

    oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
    
    #c = '.'
    x = 0
    try:        
        #while clock > 0:
        while 1:
            #c = trying()
            try:
                print x
                x += 1
                c = sys.stdin.read(1)
                break
            except IOError: pass
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
    
    return c
    
def trying():
    global clock
    clock -= 1
    print "Tic - %s"%clock
    if clock < 0:
        return '.'

    t = Timer(0.1, trying)
    t.start()
    try:
        c = sys.stdin.read(1)
        clock = 0
        return c
    except IOError: pass
    
